package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.DishMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList=new ArrayList<>();
        List<Double> turnoverList=new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        //将dataList里面元素拼接成,连接的字符串
        String dataListstr= StringUtils.join(dateList,',');

        for(LocalDate date:dateList){
            LocalDateTime begintime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endtime = LocalDateTime.of(date, LocalTime.MAX);
            Map map=new HashMap();
            map.put("begintime",begintime);
            map.put("endtime",endtime);
            map.put("status", Orders.COMPLETED);
            Double daymoney = orderMapper.sumByMap(map);
            daymoney=daymoney==null?0.0:daymoney;
            turnoverList.add(daymoney);
        }
        String turnoverListstr= StringUtils.join(turnoverList,',');


        return TurnoverReportVO.builder().dateList(dataListstr).turnoverList(turnoverListstr).build();
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        List<Integer> newUserList=new ArrayList<>();
        List<Integer> totalUserList=new ArrayList<>();
        while(!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        for(LocalDate date:dateList){
            Map map=new HashMap();
            LocalDateTime begintime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endtime = LocalDateTime.of(date, LocalTime.MAX);
            map.put("endtime",endtime);
            Integer totalUser = userMapper.countByMap(map);
            totalUserList.add(totalUser);
            map.put("begintime",begintime);
            Integer newUser = userMapper.countByMap(map);
            newUserList.add(newUser);
        }

        return UserReportVO.builder().dateList(StringUtils.join(dateList,','))
                .totalUserList(StringUtils.join(totalUserList,','))
                .newUserList(StringUtils.join(newUserList,','))
                .build();
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer> orderCountList=new ArrayList<>();
        List<Integer> validOrderCountList=new ArrayList<>();
        Integer totalOrderCount=0;
        Integer validOrderCount=0;
        Double orderCompletionRate=0.0;

        for(LocalDate date:dateList){
            LocalDateTime begintime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endtime = LocalDateTime.of(date, LocalTime.MAX);

            Integer dayorderCount = getOrderCount(begintime, endtime,null);
            if(dayorderCount==null){
                dayorderCount=0;
            }
            orderCountList.add(dayorderCount);
            Integer dayvalidOrder= getOrderCount(begintime, endtime, Orders.COMPLETED);
            if(dayvalidOrder==null){
                dayvalidOrder=0;
            }
            validOrderCountList.add(dayvalidOrder);
        }
        totalOrderCount=orderCountList.stream().reduce(Integer::sum).get();
        validOrderCount=validOrderCountList.stream().reduce(Integer::sum).get();
        orderCompletionRate=validOrderCount.doubleValue()/totalOrderCount;

        return OrderReportVO.builder().dateList(StringUtils.join(dateList,','))
                .orderCountList(StringUtils.join(orderCountList,','))
                .validOrderCountList(StringUtils.join(validOrderCountList,','))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .build();
    }

    private Integer getOrderCount(LocalDateTime begintime, LocalDateTime endtime, Integer status) {
        Map map=new HashMap();
        map.put("begintime",begintime);
        map.put("endtime",endtime);
        map.put("status",status);
        return orderMapper.countByMap(map);
    }


    /**
     * 销量排名 前十
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {

        LocalDateTime begintime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endtime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> list = orderMapper.getSalesTop10(begintime, endtime);
        String namelist="";
        String numberlist="";
        List<String> nameList=list.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList=list.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        namelist= StringUtils.join(nameList,',');
        numberlist= StringUtils.join(numberList,',');

        return SalesTop10ReportVO.builder().nameList(namelist)
                .numberList(numberlist).build();
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //先生成近30日的数据
        LocalDate now=LocalDate.now();
        LocalDate begintime=now.minusDays(30);
        LocalDate endtime = now.minusDays(1);

        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begintime, LocalTime.MIN), LocalDateTime.of(endtime, LocalTime.MAX));
        //poi读取excel
        try (InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表.xlsx");
             XSSFWorkbook excel = new XSSFWorkbook(resourceAsStream)) {

            // 创建通用字体样式
            Font font =excel.createFont();
            font.setFontName("华文仿宋");  // 设置字体
            font.setFontHeightInPoints((short)9);  // 设置字体大小
            font.setBold(false);  // 不加粗
            font.setItalic(false);  // 不斜体

            // 创建单元格样式并应用字体
            CellStyle cellStyle = excel.createCellStyle();
            cellStyle.setFont(font);

            XSSFSheet sheet = excel.getSheet("Sheet1");
            XSSFRow row2 = sheet.getRow(1);
            XSSFCell cell22 = row2.getCell(1);
            cell22.setCellStyle(cellStyle);
            cell22.setCellValue(begintime.toString()+"至"+endtime.toString());

            XSSFRow row4 = sheet.getRow(3);
            XSSFCell cell43 = row4.getCell(2);
            cell43.setCellStyle(cellStyle);
            cell43.setCellValue(businessData.getTurnover());
            XSSFCell cell45 = row4.getCell(4);
            cell45.setCellStyle(cellStyle);
            cell45.setCellValue(businessData.getOrderCompletionRate());
            XSSFCell cell47 = row4.getCell(6);
            cell47.setCellStyle(cellStyle);
            cell47.setCellValue(businessData.getNewUsers());
            XSSFRow row5 = sheet.getRow(4);
            XSSFCell cell53 = row5.getCell(2);
            cell53.setCellStyle(cellStyle);
            cell53.setCellValue(businessData.getValidOrderCount());
            XSSFCell cell55 = row5.getCell(4);
            cell55.setCellStyle(cellStyle);
            cell55.setCellValue(businessData.getUnitPrice());

            //获取30天的数据 放到excel中
            for(int i=0;i<30;i++){
                LocalDate daytime=begintime.plusDays(i);
                BusinessDataVO businessData1 = workspaceService.getBusinessData(LocalDateTime.of(daytime, LocalTime.MIN), LocalDateTime.of(daytime, LocalTime.MAX));
                XSSFRow rowi = sheet.getRow(7+i);
                XSSFCell celli1 = rowi.getCell(1);
                celli1.setCellStyle(cellStyle);
                celli1.setCellValue(daytime.toString());
                XSSFCell celli2 = rowi.getCell(2);
                celli2.setCellStyle(cellStyle);
                celli2.setCellValue(businessData1.getTurnover());
                XSSFCell celli3 = rowi.getCell(3);
                celli3.setCellStyle(cellStyle);
                celli3.setCellValue(businessData1.getValidOrderCount());
                XSSFCell celli4 = rowi.getCell(4);
                celli4.setCellStyle(cellStyle);
                celli4.setCellValue(businessData1.getOrderCompletionRate());
                XSSFCell celli5 = rowi.getCell(5);
                celli5.setCellStyle(cellStyle);
                celli5.setCellValue(businessData1.getUnitPrice());
                XSSFCell celli6 = rowi.getCell(6);
                celli6.setCellStyle(cellStyle);
                celli6.setCellValue(businessData1.getNewUsers());

            }
            excel.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
